const session = require("../../utils/session.js");
const wxm = require("../../utils/wechat_modules.js");
const toast = require("../../utils/toasts.js");
const biz = require("../../utils/bizUtils.js");
const utils = require("../../utils/utils.js");
const cart = require("../../utils/cart.js");

import {
  cut_detail,
  cut_cut,
  op_logproduct,
  card_detail,
  seller_detail,
  cut_items,
  act_query
} from "../../utils/api.js";

const app = getApp();
const globalData = app.globalData;

Page({
  data: {
    is_logined: true,
    isIphoneX: globalData.isIphoneX,
    actionSheetHidden: true,
    cartCount: 0,
    applogo: globalData.applogo
  },
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
    }
    toast.showLoading();

    if (options.salesId) {
      this.setData({
        salesId: options.salesId
      });
      if (options.salesName) {
        this.setData({
          salesName: options.salesName
        });
      }
    }

    if (options.from) {
      this.setData({
        from: options.from
      });
    }

    if (options.actId) {
      this.setData({
        actId: options.actId,
        isAct: true
      });
    }

    if (options.sellerId) {
      this.setData({
        sellerId: options.sellerId
      });
    }

    if (options.scene) {
      const scene = decodeURIComponent(options.scene);
      var params = scene.split(',');
      this.setData({
        id: params[2],
        from: 'share',
        salesId: params[3]
      });
      console.log("options.scene=" + scene);
    }

    session.login(this.refresh);
  },
  refresh: function(usr) {
    this.setData({
      user: usr
    });
    if (usr.realName) {
      this.cut();
    } else {
      this.showLoginModal();
      this.getData();
    }

  },
  onShow: function() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#FE6F3B',
    })
  },
  onUnload: function() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },
  onShareAppMessage: function(res) {
    this.opLog('SHARE');
    return wxm.commonProductShare(this, this.data.obj,'cut');
  },
  updateCartCount: function() {
    var count = cart.updateCount();
    this.setData({
      cartCount: count
    })
  },
  cut: function() {
    var that = this;

    cut_cut({
      id: this.data.id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        obj.isSelf = (obj.initId == obj.joinId);
        if (obj) {
          that.setData({
            cut: obj
          })
          that.showCut();
        } else {
          that.hideCut();
        }
      }

      that.getData();
      that.getItems();
    });
  },
  getData: function() {
    var that = this;

    cut_detail({
      id: this.data.id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        that.setDetail(obj);
        that.getCuts();
        that.updateDownTime();
      };
    });
  },
  getItems: function() {
    var that = this;
    cut_items({
      id: this.data.id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        var max = 0;
        if(obj) {
          for(var i=0;i<obj.length;i++) {
            var item = obj[i];
            if(item.price > max) {
              max = item.price;
            }
          }

          for (var i = 0; i < obj.length; i++) {
            var item = obj[i];
            if (item.price == max) {
              item.best = true;
            }
          }
        }

        that.setData({
          records: obj
        })
      };
    });
  },
  setDetail: function(obj) {
    var that = this;
    var user = this.data.user;

    obj.priceStr = utils.shortNumber(obj.originalPrice);
    if (obj.discountPrice && obj.discountPrice < obj.originalPrice) {
      obj.priceStr = utils.shortNumber(obj.discountPrice);
      obj.cutPriceStr = utils.shortNumber(obj.originalPrice);
    }
    obj.covers = obj.cover.split(",");
    obj.cover1 = obj.covers[0];
    if (obj.images) {
      obj.imageArray = obj.images.split(",");
    }
    if (obj.videos) {
      obj.videoArray = obj.videos.split(",");
      if (obj.videoArray.length > 0) {
        that.setData({
          video: {
            cover1: obj.videoArray[0]
          }
        })
      }
    }
    if (obj.params) {
      obj.paramsArray = JSON.parse(obj.params);
    }

    var isSelf = (obj.userId == user.id);
    // obj.canOnlinePay = true;
    this.setData({
      obj: obj,
      id: obj.id,
      isSelf: isSelf,
      salesId: obj.salesId,
      isMy: (obj.sellerId == this.data.user.sellerId),
      alcutprice: utils.moneyStyle(obj.originalPrice - obj.currentPrice),
      percent: (obj.originalPrice - obj.currentPrice) * 100 / (obj.originalPrice - obj.minPrice)
    });

    that.getSeller(obj.sellerId);
  },
  copy: function(e) {
    var str = e.currentTarget.dataset.text;
    var msg = e.currentTarget.dataset.title;
    this.copyOp(str, msg);
  },
  copyOp: function(str, msg) {
    wxm.copy(str, msg);

    var type = biz.getOpTypeFromStr(msg);

    this.opLog(type);
  },
  opLog: function(type) {
    var that = this;
    var param = {};
    if (this.data.salesId) {
      param.salesId = this.data.salesId;
    }
    param.objId = that.data.obj.id;
    param.sellerId = that.data.sellerId;
    if (!param.sellerId) {
      param.sellerId = that.data.obj.sellerId;
    }

    param.type = type

    setTimeout(function() {
      op_logproduct(param).then(res => {
        // console.log(res);
      });
    }, 1000) //延迟时间 这里是1秒
  },
  gotoLm: function() {
    this.opLog('CONSULT')
    if (this.data.isMy) {
      toast.show('不能给自己留言，去其他人的名片试试吧');
      return;
    }
    var that = this;

    if (this.data.salesId) {
      var name = this.data.salesName;
      wx.navigateTo({
        url: '/pages/chat/chat?id=' + this.data.salesId + '&name=' + name,
      })
      return;
    }

    wx.navigateTo({
      url: '/pages/salesList/salesList?type=selectChat&sellerId=' + this.data.sellerId,
    })
  },
  gotoHome: function() {
    biz.gotoPage('/pages/index/index');
  },
  preview: function(e) {
    var url = e.currentTarget.dataset.url;
    var key = e.currentTarget.dataset.key;

    wx.previewImage({
      urls: this.data.obj[key],
      current: url
    })
  },
  getSeller: function(sellerId) {
    if (!sellerId) {
      return;
    }
    var that = this;
    seller_detail({
      id: sellerId
    }).then(res => {
      if (res.success) {
        var obj = res.result;
        if (obj.cardType != 'BIZ') {
          return;
        }
        obj.realName = obj.name;
        obj.isCom = true;
        if (!obj.logo) {
          obj.logo = that.data.applogo;
        }
        // obj.title = '客服';
        obj.company = 'TEL.' + obj.tel;
        obj.department = '';
        obj.shortTime = '立即咨询';
        obj.onClick = 'gotoCompany';
        this.setData({
          sales: obj
        });
      };
    });
  },
  gotoCompany: function() {
    var sellerId = this.data.obj.sellerId;
    wx.navigateTo({
      url: '/pages/sellerDetail/sellerDetail?id='+sellerId,
    })
  },
  share: function() {
    this.setData({
      actionSheetHidden: false,
      productId: this.data.id,
      cardId: this.data.salesId,
      showCut:false
    });
  },
  hideShare: function() {
    this.setData({
      actionSheetHidden: true,
      showShareImg: false
    });
  },
  draw: function() {
    this.setData({
      showShareImg: true,
      productId: this.data.id,
      cardId: this.data.salesId
    });
  },
  paramsBtnClick: function() {
    var paramsType = this.data.paramsType;
    if (paramsType == 1) {
      paramsType = 0;
    } else {
      paramsType = 1;
    }

    this.setData({
      paramsType: paramsType
    })
  },
  gotoCart: function() {
    biz.gotoPage('/pages/cart/cart');
  },
  addCart: function() {
    var obj = this.data.obj;
    if (!obj.canOnlinePay) {
      wxm.showModal({
        title: '提醒',
        content: '该商品不支持在线支付，请联系客服购买',
        hideCancel: true,
        isIt: (true)
      }).then(() => {}).catch(() => {});
      return;
    }

    cart.add(obj.id, this.data.sellerId, 1, this.data.salesId);
    this.updateCartCount();
  },
  buyNow: function() {
    this.bn(0);
  },
  ptBuy: function() {
    this.bn(1);
  },
  bn: function(supportPt) {
    var obj = this.data.obj;

    wx.navigateTo({
      url: '/pages/submitOrder/submitOrder?id=' + obj.productId + '&quantity=1&activityPrice='+obj.currentPrice+'&activityId=' + obj.id + '&onlySellerId=' + obj.sellerId + (this.data.salesId ? ('&salesId=' + this.data.salesId) : ''),
    })
  },
  showCut: function() {
    this.setData({
      showCut: true
    })
  },
  hideCut: function() {
    this.setData({
      showCut: false
    })
  },
  updateDownTime: function() {
    var that = this;
    var expiredTime = this.data.obj.expiredTime;
    var now = new Date().getTime();
    if (expiredTime < now) {
      this.setData({
        expired: true
      })
      return;
    }

    var obj = this.data.obj;
    if(obj.status == 'ING' || (obj.status=='MIN' && this.data.isSelf)) {
      clearInterval(that.data.timer)
      var timer = setInterval(function () {
        now = new Date().getTime();
        if (expiredTime < now) {
          that.setData({
            expired: true
          })
          clearInterval(that.data.timer)
          return;
        }

        var expiredTimeStr = utils.downTime1(expiredTime);
        that.setData({
          expiredTimeStr: expiredTimeStr
        })
      }, 1000);
      this.setData({
        timer: timer
      });
    }
  },
  gotoProductList: function() {
    wx.navigateTo({
      url: '/pages/cardDetail/cardDetail?id=' + this.data.salesId,
    })
  },
  gotoCut: function() {
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?id=' + this.data.obj.productId,
    })
  },
  showLoginModal: function() {
    this.setData({
      isShowLoginModal: true
    });
  },
  closeLogin: function() {
    session.getUser(this);
    this.setData({
      isShowLoginModal: false
    });
    this.cut();
  },
  gotoOrder:function() {
    var obj = this.data.obj;
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id='+obj.orderId,
    })
  },
  gotoCom:function() {
    var salesId = this.data.salesId;
    wx.navigateTo({
      url: '/pages/cardDetail/cardDetail?id='+salesId,
    })
  },
  getCuts: function () {
    var that = this;
    act_query({
      sellerId: that.data.obj.sellerId,
      pageNo: 1,
      pageSize: 5,
    }).then(res => {
      if (res.success) {
        var obj = res.result.list;
        if (obj) {
          for (var i = 0; i < obj.length; i++) {
            var item = obj[i];
            item.endTimeStr = utils.tf('yyyy-MM-dd', item.activityEndTime);
            if (item.cover) {
              item.cover1 = item.cover.split(',')[0];
            }
          }
        }


        this.setData({
          cuts: obj
        });
      };
    });
  },
});